 /**
  * @description 更新用户信息
  * @author unhejing (成都-敬宇杰)
  * @date 2020-02-27 上午11:09:40
  */
const {
	validateToken
} = require('../../utils/validateToken.js')
'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event:' + event)
	let tokenRes = await validateToken(event.token)
	if (tokenRes.code != 0) {
		return tokenRes;
	}
	event.user_id = tokenRes.user_id;
	// event.user_id = "3";
	// event.name = "码云";
	// event.phone = "17695479404";
	// event.address = "锦翠南苑";
	if (event.user_id == '' || !event.user_id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少用户id'
		}
	}
	
	if (event.name == '' || !event.name) {
		return {
			success: false,
			code: -1,
			msg: '联系人姓名必填'
		}
	}
	if (event.address == '' || !event.address) {
		return {
			success: false,
			code: -1,
			msg: '联系人地址必填'
		}
	}
	if (event.phone == '' || !event.phone) {
		return {
			success: false,
			code: -1,
			msg: '联系人电话必填'
		}
	}
	
	let currentTime = new Date().getTime()
	const collection = db.collection('user_info')
	let res = collection.where({"user_id":event.user_id}).get();
	let updateRes;
	if(!res.data || res.data.length == 0){
		console.log("用户信息表不存在，新建")
		updateRes = await collection.add({
			name:event.name,// 联系人姓名
			address:event.address,// 收货地址
			phone:event.phone,// 联系人电话
			user_id:event.user_id,// 关联用户表的用户id
			create_time: currentTime,// 时间戳，创建时间
			update_time: currentTime // 时间戳，更新时间
		})
	}else{
		let userInfo = res.data[0];
		console.log("用户信息表存在，更新用户信息表")
		updateRes = await collection.doc(userInfo._id).update({
			name:event.name,// 联系人姓名
			address:event.address,// 收货地址
			phone:event.phone,// 联系人电话
			update_time: currentTime // 时间戳，更新时间
		})
	}
	console.log("修改用户信息返回参数："+JSON.stringify(updateRes))
	if(updateRes.id){
		return{
			success: true,
			code: 0,
			msg: '修改成功'
		}
	}
	return {
		success: false,
		code: -1,
		msg: '服务器内部错误'
	}
};
